import { defineStore } from "pinia"
import { Area } from "@/models/misc"
import { UserInfo } from "@/models/user"
import { userApi, miscApi} from "@/services"

const useUserInfoStore  = defineStore('UserInfo', {
    // state
    state:() =>({
        areaList: [] as Area[],
        userInfo: {} as UserInfo,
    }),
    // actions
    actions:{
        // 初始化数据
        async initData(){
            // 若没有省市区缓存数据则获取
            if (!(this.areaList && this.areaList.length>0)) {
                await this.getAreas()
            }
            
            // 若没有用户信息缓存数据则获取
            if (!(this.userInfo && this.userInfo.id)) {
                await this.getUserInfo()
            }
        },

        // 获取省市区树形列表
        async getAreas() {
            try {
                const res = await miscApi.getAreas()
                this.areaList = res
            } catch(err) {
                
            }
        },

        // 获取用户信息
        async getUserInfo() {
            try {
                const res = await userApi.getUserInfo()
                this.userInfo = res
            } catch(err) {
                
            }
        },

        // 更新用户信息
        async updateUserInfo(data:UserInfo) {
            try {
                const res = await userApi.updateUserInfo(data)
                const result = res ? res.result : false;
                if (result) {
                    this.userInfo = this.userInfo || {};
                    this.userInfo.avatar = data.avatar;
                    this.userInfo.sex = data.sex;
                    this.userInfo.area = data.area;
                    this.userInfo.bio = data.bio;
                }
                return result;
            } catch(err) {
                return false;
            }
        },
    },
    getters:{
        
    }
})

export default useUserInfoStore